package com.taobao.vsearch;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Fieldable;
import org.apache.lucene.index.Term;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.core.SolrConfig;
import org.apache.solr.core.SolrResourceLoader;
import org.apache.solr.schema.FieldType;
import org.apache.solr.schema.IndexSchema;
import org.apache.solr.schema.SchemaField;
import org.apache.solr.update.DocumentBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: caoling
 * Date: 11-3-14
 * Time: 1:42 pm
 * To change this template use File | Settings | File Templates.
 */
public class VsearchDocumentBuilder {
    public final static Logger log = LoggerFactory.getLogger(VsearchDocumentBuilder.class);
    private IndexSchema schema = null;
    //	private Map<String, String> mapping;
    protected SchemaField idField;
    protected FieldType idFieldType;

    protected SolrConfig cfg;
    protected boolean storeEnable = true;
    protected SolrResourceLoader loader;

    public VsearchDocumentBuilder() {
        try {
            cfg = new SolrConfig(null, SolrConfig.DEFAULT_CONF_FILE, this.getClass().getResourceAsStream(SolrConfig.DEFAULT_CONF_FILE));
            loader = cfg.getResourceLoader();
            schema = new IndexSchema(cfg, IndexSchema.DEFAULT_SCHEMA_FILE, getSchemaInputStream());
            System.out.println("9999999999999999999999999999999999999999999999999");
            System.out.println(schema.toString());

            storeEnable = cfg.getBool("documentStore/enable", false);

            idField = schema.getUniqueKeyField();
            idFieldType = idField != null ? idField.getType() : null;

//			InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("db-data-config.xml");
//			mapping = new DataConfig(is).field();

            log.info("analyzer={}", getAnalyzer());
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    public SolrResourceLoader getResourceLoader() {
        return loader;
    }

    public String getUniqueKey(Map<String, Object> row) {
        return row.get(schema.getUniqueKeyField().getName()).toString();
    }

    public InputStream getSchemaInputStream() {
        return this.getClass().getResourceAsStream(IndexSchema.DEFAULT_SCHEMA_FILE);
    }


    public boolean isStore() {
        return storeEnable;
    }

    public String getDocDbPath() {
        return cfg.get("documentStore/dbPath", cfg.getDataDir() != null ? cfg.getDataDir() + "/doc-db" : "doc-db");
    }

    public String getDocDbName() {
        return cfg.get("documentStore/dbName", "vsearch");
    }

    public Analyzer getAnalyzer() {
        return schema.getAnalyzer();
    }

    public Document toDocument(Map<String, Object> row) throws Exception {
        SolrInputDocument doc = DocBuilder.toSolrInputDocument(row);
        return DocumentBuilder.toDocument(doc, schema);
    }


    public Term getIdTerm(Document doc) {
        if (idField == null) {
            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Operation requires schema to have a unique key field");
        }
        Fieldable[] id = doc.getFieldables(idField.getName());
        if (id == null || id.length < 1)
            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Document is missing uniqueKey field " + idField.getName());
        if (id.length > 1)
            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Document specifies multiple unique ids! " + idField.getName());

        return new Term(idField.getName(), idFieldType.storedToIndexed(id[0]));
    }
}
